package com.xdtech.jmax.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xdtech.common.utils.ApplicationContextUtil;
import com.xdtech.common.utils.HttpClientUtil;
import com.xdtech.common.utils.RequestUtil;
import com.xdtech.jmax.model.PageView;
import com.xdtech.jmax.service.PageViewService;
import com.xdtech.jmax.vo.PageViewItem;
import com.xdtech.web.model.Pagination;
import com.xdtech.web.model.ResultMessage;
import com.xdtech.web.vo.UserAgent;

/**
 * 
 * @author max.zheng
 * @create 2015-03-12 11:01:23
 * @since 1.0
 * @see
 */
@Controller
@Scope("prototype")
public class PageViewController {
	@Autowired
	private PageViewService pageViewService;
	Log log = LogFactory.getLog(PageViewController.class);
	@RequestMapping(value="/pageView.do",params = "pageView")
	public ModelAndView skipPageView() {
		return new ModelAndView("jmax/pageView/pageView_ftl");
	}
	
	@RequestMapping(value="/pageView.do",params="loadList")
	@ResponseBody
	public Map<String, Object> loadList(HttpServletRequest request,Pagination pg) {
		Map<String, Object> results = null;
		if (StringUtils.isEmpty(request.getParameter("page"))) {
			//不分页处�?
			results = pageViewService.loadPageAndCondition(null, null);
		}else {
			results = pageViewService.loadPageAndCondition(pg, null);
		}
		
		return results;
	}
	
	@RequestMapping(value="/pageView.do",params = "editPageView")
	public ModelAndView editPageView(HttpServletRequest request,Long pageViewId) {
		if (pageViewId!=null) {
			request.setAttribute("pageViewItem", pageViewService.loadPageViewItem(pageViewId));
		}
		return new ModelAndView("jmax/pageView/editPageView_ftl");
	}
	
	@RequestMapping(value="/pageView.do",params = "savePageView")
	@ResponseBody
	public ResultMessage savePageView(PageViewItem item) {
		ResultMessage r = new ResultMessage();
		if (pageViewService.saveOrUpdatePageView(item)) {
			r.setSuccess(true);
		}else {
			r.setSuccess(false);
		}
		return r;
	}
	
	@RequestMapping(value="/pageView.do",params = "deletePageViewItems")
	@ResponseBody
	public ResultMessage deletePageViewItems(String ids) {
		ResultMessage r = new ResultMessage();
		if (StringUtils.isNotEmpty(ids)) {
			String[] tempIds = ids.split(",");
			List<Long> pageViewIds = new ArrayList<Long>();
			for (String id : tempIds) {
				pageViewIds.add(Long.valueOf(id));
			}
			pageViewService.deletePageViewInfo(pageViewIds);
			r.setSuccess(true);
		}else {
			r.setSuccess(false);
		}
		return r;
	}

	//记录浏览器相关信息及统计系统访问量
	@RequestMapping(value="/pageView.action",params = "pageViewCount")
	@ResponseBody
	public ResultMessage pageViewCount(HttpServletRequest request,String formPage) {
		ResultMessage r = new ResultMessage();
		PageView pageView = new PageView();
		String ip = RequestUtil.getClientIp(request);
		pageView.setIp(ip);
		String userAgent = request.getHeader("User-Agent");
		pageView.setBrowser(userAgent);
		pageView.setFormPage(formPage);
		try
		{
			UserAgent ua = RequestUtil.getUserAgent(userAgent);
			pageView.setBrowserType(ua!=null?ua.getBrowserType():"UNKNOWN");
			//处理根据ip获取对应地址信息
			String content = HttpClientUtil.sendPostRequestByJava("http://ip.taobao.com/service/getIpInfo.php", "ip="+ip);
			//code=0成功 1 不成功 {"code":0,"data":{"country":"中国","country_id":"CN","area":"华东","area_id":"300000","region":"福建省","region_id":"350000","city":"福州市","city_id":"350100","county":"","county_id":"-1","isp":"电信","isp_id":"100017","ip":"59.56.44.164"}}
			JSONObject json = new JSONObject(content);
			if (null != json&&json.has("data")&&"0".equals(json.getString("code")))
			{
				json = new JSONObject(json.getString("data"));
				String address = json.getString("country")+"-"+json.getString("area")+"-"+json.getString("isp")+"/"+json.getString("region")+"-"+json.getString("city");
				pageView.setAddress(address);
			}else
			{
				pageView.setAddress("未知地址");
			}
		} 
		catch (Exception e)
		{ 
			log.error(ip+"调用地址信息异常",e);
			pageView.setAddress("未知地址");
		}
		pageViewService.save(pageView);
		//统计访问量代码
		Object obj = ApplicationContextUtil.getApplication().getAttribute(formPage);
		Long pageCount = 0L;
		if (null != obj)
		{
			pageCount = (Long) obj;
		}
		pageCount++;
		ApplicationContextUtil.getApplication().setAttribute(formPage,pageCount);
		
		return r;
	}
}
